package main.ejbs;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import main.entities.User;
import main.interfaces.UserBusinessLocal;

@Stateless(name = "UserBusiness", mappedName="ejb/UserBusiness")
public class UserBusiness implements UserBusinessLocal, Serializable {
	
	/**
	 * GUID for Serializable.
	 */
	private static final long serialVersionUID = 8294319100681598554L;
	
	@PersistenceContext(name = "PatientFirstXaDsrc")
	private EntityManager _em;
	
	@Override
	public List<User> getAllUsers() {
		String queryString = "SELECT u FROM User u ORDER BY u.lName, u.fName";
		TypedQuery<User> query = null;
		List<User> resultSet = new LinkedList<User>();
		
		try {
			query = _em.createQuery(queryString, User.class);
			resultSet = query.getResultList();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
		return resultSet;
	}

	@Override
	public User getUserByUsername(String username) {
		String queryString = "SELECT u FROM User u WHERE u.uName = :username";
		TypedQuery<User> query = null;
		List<User> resultSet = null;
		
		try {
			query = _em.createQuery(queryString, User.class);
			query.setParameter("username", username);
			resultSet = query.getResultList();
		}
		catch(Exception e) {
			e.printStackTrace();
			return null;
		}
		
		if(resultSet.size() != 1) {
			return null;
		}
		
		return resultSet.get(0);
	}

	@Override
	public User saveUser(User user) {
		try {
			user = _em.merge(user);
		}
		catch(Exception e) {
			e.printStackTrace();
			return null;
		}
		
		return user;
	}

	@Override
	public void addUser(User user) {
		user.setId(null);
		
		try {
			_em.persist(user);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteUser(User user) {
		try {
			user = _em.find(User.class, user.getId());
			_em.remove(user);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

}
